package cn.yllr.tomgxianghui.controller;

import cn.yllr.tomgxianghui.entity.User;
import cn.yllr.tomgxianghui.model.ShowCook;
import cn.yllr.tomgxianghui.service.MailService;
import cn.yllr.tomgxianghui.service.UserService;
import cn.yllr.tomgxianghui.util.MD5Util;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;

/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2021-12-21 00:06:35
 */
@Controller
@RequestMapping("user")
public class UserController {
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;
    /**
     * 邮件服务对象
     */
    @Resource
    private MailService mailService;

    public void render(String leftInfo, String rightInfo1, String rightInfo2, String api1, String api2,
                       Model model) {
        model.addAttribute("leftInfo", leftInfo);
        model.addAttribute("rightInfo1", rightInfo1);
        model.addAttribute("rightInfo2", rightInfo2);
        model.addAttribute("api1", api1);
        model.addAttribute("api2", api2);
    }

    /**
     * 登录
     *
     * @param account
     * @param password
     * @param checkCode
     * @param session
     * @param redirect
     * @return
     */
    @PostMapping("/login.do")
    public String login(@RequestParam("username") String account, String password, String checkCode,
                        HttpSession session, RedirectAttributes redirect) {
        //使用卫语句，减少else出现，做排除法，不满足直接跳出，不做过多判断
        if (account != null && password != null && checkCode != null) {
            if (!checkCode.equalsIgnoreCase(session.getAttribute("randomcode_key").toString())) {
                redirect.addFlashAttribute("result", "验证码错误请重新输入");
                return "redirect:/login.html";
            }
            User user;
            /*邮箱正则*/
            String email_reg = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
            if (Pattern.matches(email_reg, account)) {
                user = this.userService.queryByEmail(account);
            } else {
                user = this.userService.queryById(account);
            }

            if (user == null) {
                redirect.addFlashAttribute("result", "账号不存在");
                return "redirect:/login.html";
            }
            if (!MD5Util.EncodeByMD5(password).equals(user.getPassword())) {
                redirect.addFlashAttribute("result", "密码错误，请重新输入");
                return "redirect:/login.html";
            }
            if ("厨师".equals(user.getRole())) {
                session.setAttribute("role", "厨师");
                session.setAttribute("username", user.getAccount());
                return "redirect:/dishes/recommend";
            }
            if ("顾客".equals(user.getRole())) {
                session.setAttribute("role", "顾客");
                session.setAttribute("username", user.getAccount());
                return "redirect:/dishes/recommend";
            }
        }
        redirect.addFlashAttribute("result", "请填写完成如下表单再提交");
        return "redirect:/login.html";
    }

    /**
     * 发送注册邮件
     *
     * @param email
     * @param session
     * @return
     */
    @RequestMapping("sendEmail")
    @ResponseBody
    public String sendEmail(String email, HttpSession session) {
        if (email == null || "".equals(email)) {
            return "邮箱号不能为空";
        }
        if (userService.checkEmail(email)) {
            return "该邮箱号已经被注册了，请更换邮箱";
        }
        String emailCheckCode = UUID.randomUUID().toString().replace("-", "").substring(1, 7);
        String content = "您的邮箱验证码为：" + emailCheckCode + "，有效期为15分钟";
        session.setAttribute("emailCheckCode", emailCheckCode);
        //设置15分钟超时时间
        session.setMaxInactiveInterval(900);
        mailService.sendSimpleTextMailActual("同乡烩用户注册", content, new String[]{email}, null, null, null);
        return "验证码已经发送至" + email + "请注意查收";
    }

    /**
     * 注册
     *
     * @param username
     * @param password
     * @param email
     * @param phoneNumber
     * @param role
     * @param checkCode
     * @param realname
     * @param session
     * @param redirect
     * @return
     */
    @PostMapping("/register.do")
    public String register(String username, String password, String email, String phoneNumber,
                           String role, String checkCode, String realname, String emailCheckCode,
                           HttpSession session, RedirectAttributes redirect) {
        if (username != null && password != null && email != null && phoneNumber != null && role != null && checkCode != null) {
            if (!checkCode.equalsIgnoreCase(session.getAttribute("randomcode_key").toString())) {
                redirect.addFlashAttribute("result", "验证码输入错误请重新输入");
                return "redirect:/register.html";
            }
            if (!emailCheckCode.equals(session.getAttribute("emailCheckCode").toString())) {
                redirect.addFlashAttribute("result", "邮箱验证码输入错误请重新输入");
                return "redirect:/register.html";
            }
            if (userService.queryById(username) != null) {
                redirect.addFlashAttribute("result", "用户名已经被注册请重新输入用户名");
                return "redirect:/register.html";
            }
            User user = new User();
            user.setAccount(username);
            /*MD5加密*/
            user.setPassword(MD5Util.EncodeByMD5(password));
            user.setEmail(email);
            user.setPhone(phoneNumber);
            user.setRole(role);
            user.setRealname(realname);
            userService.insert(user);
            redirect.addFlashAttribute("msg", "注册成功现在开始登录吧");
            return "redirect:/login.html";

        }
        redirect.addFlashAttribute("result", "输入不能为空");
        return "redirect:/register.html";
    }


    /**
     * 退出登录
     *
     * @param session
     * @return
     */
    @RequestMapping("/logout.do")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/login.html";
    }

    /**
     * 异步刷新，通过关键词查询厨师
     *
     * @param keyWord
     * @param model
     * @return
     */
    @RequestMapping("selectCookByName")
    public String selectCookByName(@RequestParam("name") String keyWord, Model model) {
        if (keyWord == null || "".equals(keyWord)) {
            return "/index";
        }
        List<ShowCook> cooks = userService.selectCookByName(keyWord);
        render("厨师搜索结果", "查看厨师推荐", "查看所有厨师", "/user/selectRecommendCooks", "/user/selectAllCooks", model);
        model.addAttribute("cooks", cooks);
        return "/index::showInfo";
    }

    /**
     * 异步刷新，显示全部厨师
     *
     * @param model
     * @return
     */
    @RequestMapping("selectAllCooks")
    public String selectAllCooks(Model model) {
        List<ShowCook> cooks = userService.selectAllCooks();
        render("所有厨师", "查看厨师推荐", "查看精品推荐", "/user/selectRecommendCooks", "/dishes/syncRecommend", model);
        model.addAttribute("cooks", cooks);
        return "/index::showInfo";
    }

    /**
     * 异步刷新，显示推荐厨师页面
     *
     * @param model
     * @return
     */
    @RequestMapping("selectRecommendCooks")
    public String selectRecommendCooks(Model model) {
        List<ShowCook> cooks = userService.selectRecommendCooks(10);
        render("厨师推荐", "查看全部厨师", "查看精品推荐", "/user/selectAllCooks", "/dishes/syncRecommend", model);
        model.addAttribute("cooks", cooks);
        return "/index::showInfo";
    }

    //修改用户信息
    @RequestMapping("/toAccount")
    public String toAccount(HttpSession session, Model model) {
        if (session.getAttribute("username") != null) {
            User user = userService.queryById(session.getAttribute("username").toString());
            model.addAttribute("user", user);
        }
        return "user_center/user_account";
    }

    @RequestMapping("/updateUser/{account}")
    public String updateUser(@PathVariable("account")String account,User user) {
        if (userService.queryById(account).getPassword().equals(user.getPassword())) {
            userService.update(user);
        }
        user.setPassword(MD5Util.EncodeByMD5(user.getPassword()));
        userService.update(user);
        return "redirect:/user_main.html";
    }

}
